package com.nulp.psycho.mail;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.nulp.psycho.db.model.User;


public class EmailUtility implements Runnable {
	String subject;
	String message;
	List<String> toAddres = new ArrayList<String>();

	public void sendEmail(String subject, String message, User... users) throws AddressException, MessagingException {
		this.message = message;
		this.subject = subject;

		for (User user : users) {
			toAddres.add(user.getEmail());
		}
		Thread thread = new Thread(this);
		thread.start();

	}

	@Override
	public void run() {

		try {

			final Properties properties = new Properties();
			try {
				properties.load(EmailUtility.class.getClassLoader().getResourceAsStream("email.properties"));
			} catch (IOException e) {
				e.printStackTrace();
			}

			Authenticator auth = new Authenticator() {
				public PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication(properties.getProperty("mail.user"), properties.getProperty("mail.password"));
				}
			};

			Session session = Session.getInstance(properties, auth);

			Message msg = new MimeMessage(session);

			msg.setFrom(new InternetAddress(properties.getProperty("email")));
			InternetAddress[] addr = new InternetAddress[toAddres.size()];
			for (int i = 0; i < addr.length; i++) {
				addr[i] = new InternetAddress(toAddres.get(i));
			}
			msg.setRecipients(Message.RecipientType.TO, addr);
			msg.setSubject(subject);
			msg.setSentDate(new Date());
			msg.setContent(message, "text/html; charset=utf-8");
			Transport.send(msg);
		} catch (AddressException e) {
			e.printStackTrace();
		} catch (MessagingException e) {
			e.printStackTrace();
		}
	}

}
